package com.hanyxx.thread;

import lombok.SneakyThrows;

import java.util.ArrayList;
import java.util.List;

/**
 * @author layman
 * @date 2021/2/7
 */
public class Demo13 {
    public static void main(String[] args) throws InterruptedException {
        Chef chef = new Chef();
        Consumer consumer = new Consumer();
        chef.setName("大厨食神");
        consumer.setName("吃货layman");
        consumer.start();
        Thread.sleep(100);
        chef.start();
    }
}
class Food{
    private static volatile List<String> baozi = new ArrayList<>();
    private static volatile boolean isEmpty = true;
    private static Long sleepTime = 2000L;
    private static Object lock = new Object();
    public static void produce() throws InterruptedException {
        synchronized (lock) {
            if (isEmpty) {
                for (int i = 0; i < 5; i++) {
                    baozi.add("第 "+(i + 1) + " 个包子");
                }
                System.out.println("生产了五个包子，通知吃货。");
                System.out.println("--------------------------");
                Thread.sleep(sleepTime);
                isEmpty = false;
                lock.notify();
            }else if(!isEmpty){
                System.out.println("包子还没吃完，可以继续休息。");
                System.out.println("--------------------------");
                Thread.sleep(sleepTime);
                lock.wait();
            }
        }
    }
    public static void consumer() throws InterruptedException {
        synchronized (lock) {
            if (!isEmpty) {
                baozi.clear();
                System.out.println("吃货把包子吃光了，通知大厨做包子。");
                System.out.println("--------------------------");
                Thread.sleep(sleepTime);
                isEmpty = true;
                lock.notify();
            }else if(isEmpty){
                System.out.println("没有包子，等着大厨做包子。");
                System.out.println("--------------------------");
                Thread.sleep(sleepTime);
                lock.wait();
            }
        }
    }
}
//生产者
class Chef extends Thread{
    @SneakyThrows
    @Override
    public void run() {
        while (true){
            Food.produce();
        }
    }
}
//消费者
class Consumer extends Thread{
    @SneakyThrows
    @Override
    public void run() {
        while (true){
            Food.consumer();
        }
    }
}
